package com.taotao.web.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.ApiService.ApiService;
import com.taotao.common.ApiService.HttpClientResult;
import com.taotao.common.JedisService.JedisService;
import com.taotao.web.pojo.ItemDesc;

@Service
public class ItemDescService { 
	@Autowired
	ApiService apiService;
	@Autowired
	PropertieService propertieService;
	@Autowired
	JedisService jedisService;
	/**
	 * 根据itemId查询商品详情
	 * @param itemId
	 * @return
	 */
	public ItemDesc queryByItemId(Long itemId){
		// 先从缓存中查询商品详情, 有就直接返回
		if(this.getItemDescByRedis(itemId) != null) return this.getItemDescByRedis(itemId);
		try {
			String url = StringUtils.replace(propertieService.TT_MANAGE_ITEMDESC, "{itemId}", itemId.toString());
			HttpClientResult result = apiService.doGet(url);
			String content = result.getContent();
			ItemDesc itemDesc = PropertieService.MAPPER.readValue(content, ItemDesc.class);
			try {
				// 将数据存到redis缓存中
				String key = StringUtils.replace(propertieService.TAOTAO_WEB_JEDISCACHED_ITEMDESCKEY, "{itemId}",itemId.toString());
				jedisService.setExpr(key, propertieService.TAOTAO_WEB_JEDISCACHED_ITEMDESCLIVE, content);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return itemDesc;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 从缓存中查询商品详情
	 * @param itemId
	 * @return
	 */
	public ItemDesc getItemDescByRedis(Long itemId) {
		try {
			// 先从缓存中查询
			String key = StringUtils.replace(propertieService.TAOTAO_WEB_JEDISCACHED_ITEMDESCKEY, "{itemId}",itemId.toString());
			String itemDescJson = jedisService.get(key);
			if (StringUtils.isNotBlank(itemDescJson)) {
				// 缓存中找到后直接返回
				return PropertieService.MAPPER.readValue(itemDescJson, ItemDesc.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}




